package io.renren.modules.table.service.impl;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xiaoleilu.hutool.date.DateUtil;
import com.xiaoleilu.hutool.util.CollectionUtil;
import com.xiaoleilu.hutool.util.NumberUtil;

import io.renren.common.utils.R;
import io.renren.modules.com.dao.ComCollectionRecordDao;
import io.renren.modules.com.dao.ComContractDao;
import io.renren.modules.com.dao.ComCrChargingitemDao;
import io.renren.modules.com.entity.ComCrChargingitemEntity;
import io.renren.modules.table.entity.AllocationSummaryEntity;
import io.renren.modules.table.service.StatementOfAccountsReceivableService;

@Service("statementOfAccountsReceivableService")
public class StatementOfAccountsReceivableServiceImpl implements StatementOfAccountsReceivableService {

	@Autowired
	private ComContractDao comContractDao;

	@Autowired
	private ComCollectionRecordDao comCollectionRecordDao;

	@Autowired
	private ComCrChargingitemDao comCrChargingitemDao;

	public R initialization() {
		return initializationPrivate();
	}

	private R initializationPrivate() {
		Map<String, Object> map = new HashMap<String, Object>();
		SimpleDateFormat sdfwyj = new SimpleDateFormat("yyyy");
		SimpleDateFormat sdfpfp = new SimpleDateFormat("yyyy-MM");
		SimpleDateFormat sdfqyd = new SimpleDateFormat("yyyy年MM月");
		Date nowDate = new Date();
		map.put("dateYearS", sdfwyj.format(nowDate));
		map.put("dateYearE", sdfwyj.format(nowDate));
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(nowDate);
		calendar.set(Calendar.MONTH, calendar.getActualMinimum(Calendar.MONTH));
		map.put("dateMonthS", sdfpfp.format(calendar.getTime()));
		Date sd = calendar.getTime();
		calendar.set(Calendar.MONTH, calendar.getActualMaximum(Calendar.MONTH));
		map.put("dateMonthE", sdfpfp.format(calendar.getTime()));
		Date ed = calendar.getTime();
		// 初始化jqgrid标题名
		map.put("caption", "应收款汇总报表(" + sdfqyd.format(sd) + "至" + sdfqyd.format(ed) + ")");
		return R.ok(map);
	}

	public R changeJqGrid(AllocationSummaryEntity allocationSummary) {
		return changeJqGridPrivate(allocationSummary);
	}

	private R changeJqGridPrivate(AllocationSummaryEntity allocationSummary) {
		Map<String, Object> map = new HashMap<String, Object>();
		String dateType = allocationSummary.getYearMonth();
		Date sd = null;
		Date ed = null;
		SimpleDateFormat sdfwyj = null;
		SimpleDateFormat sdf = null;
		if (StringUtils.equals("1", dateType)) {
			sdfwyj = new SimpleDateFormat("yyyy-MM");
			sdf = new SimpleDateFormat("yyyy年MM月");
			sd = DateUtil.parse(allocationSummary.getDateMonthS(), sdfwyj);
			ed = DateUtil.parse(allocationSummary.getDateMonthE(), sdfwyj);
		}
		if (StringUtils.equals("2", dateType)) {
			sdfwyj = new SimpleDateFormat("yyyy");
			sdf = new SimpleDateFormat("yyyy年");
			sd = DateUtil.parse(allocationSummary.getDateYearS(), sdfwyj);
			ed = DateUtil.parse(allocationSummary.getDateYearE(), sdfwyj);
		}
		// 初始化jqgrid标题名
		map.put("caption", "应收款汇总报表(" + sdf.format(sd) + "至" + sdf.format(ed) + ")");
		return R.ok(map);
	}

	public List<Map<String, Object>> queryList(Map<String, Object> map) {
		return queryListPrivate(map);
	}

	private List<Map<String, Object>> queryListPrivate(Map<String, Object> map) {
		if (null != map.get("items") && StringUtils.isNotBlank(map.get("items").toString().trim())
				&& !StringUtils.equals("点击选择...", map.get("items").toString().trim())) {
			List<String> itemList = Arrays.asList(map.get("items").toString().replace(" ", "").split(","));
			map.put("itemList", itemList);
		}
		String sd = null;
		String ed = null;
		if (StringUtils.equals("1", map.get("yearMonth").toString())) {
			sd = map.get("dateMonthS").toString();
			ed = map.get("dateMonthE").toString();
		}
		if (StringUtils.equals("2", map.get("yearMonth").toString())) {
			sd = map.get("dateYearS").toString();
			ed = map.get("dateYearE").toString();
		}
		map.put("sd", sd);
		map.put("ed", ed);
		List<Map<String, Object>> chinaJoy = new ArrayList<Map<String, Object>>();
		Double a = null;
		Double b = null;
		List<String> contractNoList = comCollectionRecordDao.ftp(map);
		if (CollectionUtil.isEmpty(contractNoList)) {
			return null;
		}
		map.put("contractNoList", contractNoList);
		List<ComCrChargingitemEntity> comCrChargingitemList = comCrChargingitemDao.turnover(map);
		if (CollectionUtil.isEmpty(comCrChargingitemList)) {
			return null;
		}
		Map<String, String> contractOld = contractOld();
		Map<String, String> contractNew = contractNew();
		for (ComCrChargingitemEntity comCrChargingitemEntity : comCrChargingitemList) {
			Map<String, Object> bilibli = new HashMap<String, Object>();
			bilibli.put("item", comCrChargingitemEntity.getChargingItem());
			a = null;
			map.put("ftpOld", contractOld.get(comCrChargingitemEntity.getChargingItem()));
			map.put("ftpNew", contractNew.get(comCrChargingitemEntity.getChargingItem()));
			a = comContractDao.ftp(map);
			if (null == a || a == 0) {
				a = 0.0;
				bilibli.put("yingsje", "");
			} else {
				bilibli.put("yingsje", a);
			}
			if (null == comCrChargingitemEntity.getPayAmount()) {
				b = 0.0;
				bilibli.put("yisje", "");
			} else {
				b = comCrChargingitemEntity.getPayAmount();
				bilibli.put("yisje", b);
			}
			if (null != map.get("amaze") && StringUtils.isNotBlank(map.get("amaze").toString())) {
				if (StringUtils.equals("1", map.get("amaze").toString())) {
					if (NumberUtil.sub(a, b) != 0) {
						continue;
					}
				}
				if (StringUtils.equals("2", map.get("amaze").toString())) {
					if (NumberUtil.sub(a, b) == 0) {
						continue;
					}
				}
			}
			bilibli.put("wsje", NumberUtil.sub(a, b));
			chinaJoy.add(bilibli);
		}
		return chinaJoy;
	}

	private Map<String, String> contractOld() {
		Map<String, String> map = new HashMap<String, String>();
		map.put("租金", "total_price");
		map.put("物业费", "total_manage");
		map.put("管理费", "total_property");
		map.put("公共能耗费", "total_energy");
		map.put("居间服务费", "total_inter");
		map.put("保证金", "total_bond");
		map.put("停车费", "total_stop");
		map.put("其他", "total_other");
		map.put("租场费", "total_other1");
		return map;
	}
	
	private Map<String, String> contractNew() {
		Map<String, String> map = new HashMap<String, String>();
		map.put("租金", "stotal_price");
		map.put("物业费", "stotal_manage");
		map.put("管理费", "stotal_property");
		map.put("公共能耗费", "stotal_energy");
		map.put("居间服务费", "stotal_inter");
		map.put("保证金", "stotal_bond");
		map.put("停车费", "stotal_stop");
		map.put("租场费", "stotal_other1");
		map.put("其他", "stotal_other");
		return map;
	}

	public int queryTotal(Map<String, Object> map) {
		return comCrChargingitemDao.turnoverTotal(map);
	}

	public void export(OutputStream out, Map<String, Object> map) {
		exportPrivate(out, map);
	}

	private void exportPrivate(OutputStream out, Map<String, Object> map) {
		// 声明一个工作薄
		HSSFWorkbook workbook = new HSSFWorkbook();
		// 生成一个表格
		HSSFSheet sheet = workbook.createSheet();
		// 生成数字样式
		HSSFCellStyle numberStyle = workbook.createCellStyle();
		numberStyle.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
		// 生成文字样式
		HSSFCellStyle style = workbook.createCellStyle();
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		// 生成一个字体
		HSSFFont font = workbook.createFont();
		font.setFontHeightInPoints((short) 12);
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		// 把字体应用到当前的样式
		style.setFont(font);
		// 生成excel内容
		HSSFRow rowOne = sheet.createRow(0);
		HSSFCell cell = null;
		cell = rowOne.createCell(0);
		cell.setCellStyle(style);
		cell.setCellValue("收款项目");
		cell = rowOne.createCell(1);
		cell.setCellStyle(style);
		cell.setCellValue("应收金额");
		cell = rowOne.createCell(2);
		cell.setCellStyle(style);
		cell.setCellValue("已收金额");
		cell = rowOne.createCell(3);
		cell.setCellStyle(style);
		cell.setCellValue("未收金额");
		List<Map<String, Object>> chinaJoy = queryList(map);
		for (int i = 0; i < chinaJoy.size(); i++) {
			Map<String, Object> alphabetBear = chinaJoy.get(i);
			HSSFRow row = sheet.createRow(i + 1);
			cell = row.createCell(0);
			cell.setCellStyle(style);
			cell.setCellValue(alphabetBear.get("item").toString());
			cell = row.createCell(1);
			cell.setCellStyle(style);
			cell.setCellValue(alphabetBear.get("yingsje").toString());
			cell = row.createCell(2);
			cell.setCellStyle(style);
			cell.setCellValue(alphabetBear.get("yisje").toString());
			cell = row.createCell(3);
			cell.setCellStyle(style);
			cell.setCellValue(alphabetBear.get("wsje").toString());
		}
		try {
			workbook.write(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
